module.exports = (EdtApi) => {
    "use strict";
    let chatId = "", count = 0;
    function isGroup() {
        return !!document.querySelector('#detail-header span.css-1jxf684.r-dnmrzs.r-1udh08x.r-3s2u2q.r-bcqeeo.r-1ttztb7.r-qvutc0.r-poiln3[data-testid="DMGroupConversationTitle"]');
    }
    async function getChatId(times = 0) {
        let url = window.location.href;
        const regex = /\/messages\/(\d+-\d+|\d+)\/?/;
        const match = regex.exec(url);
        let id = '';
        try {
            if (match) id = match[1];
        } catch (error) {
            console.log('获取对话id失败', error)
        }
        if (id && id != chatId) return id;
        await EdtApi.sleep(50);
        if (times > 10) return id;
        times++;
        return getChatId(times);
    }
    return {
        config: {
            friendList: 'section>div.css-175oi2r>div[role="tablist"],a[data-testid="AppTabBar_DirectMessage_Link"],button[data-testid="nextButton"],button[data-testid="sendDMFromProfile"],div[data-testid="DMDrawer"] div[data-viewportview="true"]>div>section[role="region"]',
            chat: 'section[aria-labelledby="detail-header"][role="region"],div.css-175oi2r.r-12vffkv>div[data-testid="DMDrawer"]',
            input: 'div.DraftEditor-root div.DraftEditor-editorContainer div.public-DraftEditor-content[data-testid="dmComposerTextInput"]',
            msgBox: 'div[data-testid="DmScrollerContainer"]',
            inMsg: 'div[data-testid="cellInnerDiv"] div.r-k200y>div[data-testid="tweetText"]:not(.trans-inited)',
            outMsg: 'div[data-testid="cellInnerDiv"] div.r-173mn98>div[data-testid="tweetText"]:not(.trans-inited)',
            sendBtn: 'aside[role="complementary"] button[role="button"][data-testid="dmComposerSendButton"]',
            setting: "aside>div.css-175oi2r.r-1awozwy.r-1sw30gj.r-1867qdf.r-18u37iz.r-l00any.r-jusfrs.r-tuq35u.r-1h0ofqe>div.css-175oi2r.r-1kihuf0.r-16y2uox.r-1wbh5a2",
            tips: {
                in: '#detail-header',
                out: 'aside[role="complementary"]'
            },
            crm: {
                // listener: '#LeftColumn-main',
                top: '#detail-header>div.css-175oi2r',
                left: ""
            },
            placeholder: {
                selector: "div.public-DraftEditorPlaceholder-root>div.public-DraftEditorPlaceholder-inner",
                delay: 200,
                update: true
            },
            autoCount: 20,
        },
        getUnread() {
            count = 0;
            const noticeEl = document.querySelector('[data-testid=AppTabBar_Notifications_Link] div div div');
            if (noticeEl) count += EdtApi.safeParseInt(noticeEl.textContent);
            const DMElement = document.querySelector('[data-testid=AppTabBar_DirectMessage_Link] div div div');
            if (DMElement) {
                count += EdtApi.safeParseInt(DMElement.textContent);
            } else {
                const els = document.querySelectorAll('.css-175oi2r.r-16y2uox.r-f8sm7e.r-13qz1uu section.css-175oi2r .css-175oi2r.r-sdzlij.r-lrvibr.r-615f2u.r-u8s1d.r-3sxh79.r-1phboty.r-rs99b7.r-l5o3uw.r-1or9b2r.r-1lg5ma5.r-5soawk')
                count += els.length
            }
            return count;
        },
        getChatInfo() {
            return new Promise(async (resolve) => {
                chatId = await getChatId();
                resolve({ id: chatId, isGroup: isGroup() });
            });
        },
        getChatTitle(chatEl = document) {
            let titleEl = chatEl.querySelector('#detail-header div.css-175oi2r>span.css-1jxf684');
            if (!titleEl) return "";
            if (!titleEl.querySelector('img')) return titleEl.textContent || '';
            let title = "";
            titleEl.childNodes?.forEach(child => {
                if (child.nodeName == 'SPAN') {
                    title += child.textContent || "";
                } else if (child.nodeName == 'IMG') {
                    title += child.getAttribute("alt") || "";
                }
            });
            return title;
        },
        getText(msgBox) {
            let text = '';
            try {
                if (msgBox.querySelector('img')) {
                    let childNodes = msgBox.childNodes;
                    childNodes?.forEach(child => {
                        if (child.nodeName == "IMG") {
                            text += child.getAttribute("alt") || "";
                        } else {
                            text += child.textContent;
                        }
                    });
                } else {
                    text = msgBox.textContent;
                }
            } catch (error) {
                console.error(error);
            }
            return text;
        },
        getIptMsg(inputEl) {
            if (!inputEl) return '';
            try {
                let texts = [], items = inputEl.querySelectorAll('div[data-contents="true"]>div[data-editor]');
                let len = items.length, children;
                items?.forEach((item, index) => {
                    children = item.querySelectorAll("div.public-DraftStyleDefault-ltr>span");
                    children?.forEach(child => {
                        texts.push(child.textContent);
                    });
                    if (index < len - 1) texts.push("\n");
                });
                if (0 == texts.length) return "";
                return texts.join("\n");
            } catch (error) {
                console.error(error);
            }
            return "";
        },
        inputMsg(inputEl, msg) {//必须
            return new Promise((resolve) => {
                inputEl?.focus();
                document.execCommand("selectAll");
                EdtApi.sleep(20).then(() => {
                    navigator.clipboard.writeText(msg).then(() => {
                        document.execCommand("paste");
                        resolve(true);
                    }).catch(() => {
                        resolve(false);
                    });
                });
            });
        },
        getUserInfo() {
            try {
                let userEl = document.querySelector(
                    'header div.css-175oi2r.r-1mlwlqe.r-1udh08x.r-417010.r-1p0dtai.r-1d2f490.r-u8s1d.r-zchlnj.r-ipm5af[aria-label]'
                );
                let phoneEl = document.querySelector(
                    'header nav>a[data-testid="AppTabBar_Profile_Link"]'
                );
                let userName = userEl?.getAttribute("aria-label") || "";
                let avatarEl = userEl?.querySelector("img.css-9pa8cd");
                let avatar = avatarEl?.getAttribute("src") || "";
                let account = phoneEl?.getAttribute("href")?.replace("/", "") || "";
                return {
                    avatar,
                    userName,
                    account
                };
            } catch (error) {
                return null;
            }
        }
    }
};